package cn.i7baozh.starter.common.controller;

import com.google.common.collect.Lists;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.web.method.support.HandlerMethodReturnValueHandler;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter;

import java.util.List;

/**
 * 统一返回值抽象处理器
 * @author: baoqi.zhang
 * @date: 2020/6/1 20:17
 */
public abstract class AbstractHandler implements BeanPostProcessor {

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        if (bean instanceof RequestMappingHandlerAdapter) {
            RequestMappingHandlerAdapter adapter = (RequestMappingHandlerAdapter) bean;
            List<HandlerMethodReturnValueHandler> returnValueHandlers = adapter.getReturnValueHandlers();
            List<HandlerMethodReturnValueHandler> handlers = Lists.newArrayList();
            handlers.add(0, getHandler());
            for (HandlerMethodReturnValueHandler returnValueHandler : returnValueHandlers) {
                handlers.add(returnValueHandler);
            }
            adapter.setReturnValueHandlers(handlers);

        }
        return bean;
    }

    /**
     * 获取返回值处理器
     * @return
     */
    protected abstract HandlerMethodReturnValueHandler getHandler();

}
